package seismosurfer.database;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import seismosurfer.data.CountryData;
import seismosurfer.util.SeismoException;

/**
 * A DAO object that encapsulates all access to the
 * COUNTRY table.
 *
 */
public class CountryDAO {

    private static final String COUNTRIES = " SELECT councode, name FROM country order by name ";

    /**
     * Default empty constructor.
     *
     */
    public CountryDAO() {

    }

    /**
     * Loads a row from the database into a CountryData object.
     * 
     * @param rs the resultset from which the row will be loaded
     * @return A CountryData object which contains the data of a row.
     * @throws SQLException
     */
    public static CountryData load(ResultSet rs) throws SQLException {
        CountryData cd = new CountryData();
        cd.setCode(rs.getString(1));
        cd.setName(rs.getString(2));

        return cd;
    }

    /**
     * Retrieves a list with all the countries data.
     * 
     * @return A list with all the countries data.
     */
    public static List getCountries() {
        List result = new ArrayList();
        ResultSet rs = null;
        PreparedStatement ps = null;

        try {
            ps = DB.prepare(COUNTRIES);
            rs = ps.executeQuery();

            while (rs.next()) {
                result.add(load(rs));
            }

            return result;

        } catch (SQLException ex) {
            throw new SeismoException(ex);
        } finally {
            DB.cleanUp(ps, rs);
        }

    }

}